﻿using System;
using System.Collections;
using System.Collections.Generic;
using AutoChess;
using UnityEngine;
using UnityEngine.Serialization;
using Yunchang;

class AutoChessFieldViewCtr : MonoBehaviour, IVisualRenderer<AutoChessFieldCtr, AutoChessFieldViewCtr>
{
    private static AutoChessFieldViewCtr ins;
    public static AutoChessFieldViewCtr Ins
    {
        get { return ins; }
    }

    private AutoChessManager acMger;
    /// <summary>当前的战场数据 </summary>
    [FormerlySerializedAs("gameField")] public AutoChessFieldCtr gameAutoChessField;
    
    public bool SwitchCameraToUI;

    /// <summary>格子节点 </summary>
    private Transform gridUnitRoot;
    /// <summary>英雄节点 </summary>
    private Transform heroUnitRoot;
    /// <summary>船的节点 </summary>
    private Transform shipUnitRoot;
    /// <summary>特效节点</summary>
    private Transform sceneEffectRoot;

    private AutoChessConfig sceneConfig;
    //private RendererPool renderPool;
    /// <summary>手动操作的相关逻辑 </summary>
    private FieldOperationHelper operationHelper;
    //模型加载
    private LoadEventManager loadEventManager;
    //一些流程逻辑整合
    private ActionQueueCtr actionCtr = new ActionQueueCtr();

    public ActionQueueCtr ActionCtr
    {
        get { return actionCtr; }
    }
    public AutoChessConfig SceneConfig
    {
        get { return sceneConfig; }
    }
    public Transform HeroUnitRoot
    {
        get { return heroUnitRoot; }
    }
    public Transform ShipUnitRoot
    {
        get { return shipUnitRoot; }
    }
    public Transform SceneEffectRoot
    {
        get { return sceneEffectRoot; }
    }
    internal void OpenDuanPage()
    {
        StopCoroutine(OpenDuaninPage());
        StartCoroutine(OpenDuaninPage());
    }

    internal void OpenResultListPage()
    {
        Invoke("OpenPage", 0.3f);
    }
    IEnumerator OpenDuaninPage()
    {
        yield return new WaitForSeconds(0.5f);
        EventManager.TriggerEvent<CommonEffectResId>(CommonEvent.ON_PLAY_UI_EFFECT, CommonEffectResId.AC_UI_150_zizhouqi_zhandojieshu);
        yield return new WaitForSeconds(AutoChessFieldViewCtr.ins.SceneConfig.ganOverEffectTime);
        PageManager.Instance.OpenPage("AutoChessDuanPage");
    }

    private void OpenPage()
    {
        PageManager.Instance.OpenPage("AutoChessBillingInfoPage");
    }

    public FieldOperationHelper InputCtr
    {
        get { return operationHelper; }
    }
    public LoadEventManager LoadEventManager { get { return loadEventManager; } }

    void Awake()
    {
        ins = this;
    }
    
    /// <summary>
    /// 初始化战场渲染器
    /// </summary>
    public void Init(AutoChessManager autoChessManager)
    {
        Yunchang.EventManager.AddEventListener<bool, List<GameObject>>(CommonEvent.PUSH_SHOP_GRID_ROOT, RegisterShopGridRoot);

        CreateDummyPoint();
        renderPool = new RendererPool();
        operationHelper = new FieldOperationHelper();
        this.acMger = autoChessManager;

        loadEventManager = new LoadEventManager();
        loadEventManager.Initialize(this);
        actionCtr = new ActionQueueCtr();
    }

    private void CreateDummyPoint()
    {
       var gridGo = AvatarDefine.CreateDummyPoint(AvatarDefine.GetChessRootDummyPointName(ChessDummyPoint.DM_ACGRID),transform,Vector3.zero);
       var heroGo =AvatarDefine.CreateDummyPoint(AvatarDefine.GetChessRootDummyPointName(ChessDummyPoint.DM_ACHERO),transform,Vector3.zero);
       var shipGo = AvatarDefine.CreateDummyPoint(AvatarDefine.GetChessRootDummyPointName(ChessDummyPoint.DM_ACSHIP),transform,Vector3.zero);
       var effectGo = AvatarDefine.CreateDummyPoint(AvatarDefine.GetChessRootDummyPointName(ChessDummyPoint.DM_EffectRoot),transform,Vector3.zero);
       gridUnitRoot = gridGo.transform;
       heroUnitRoot = heroGo.transform;
       shipUnitRoot = shipGo.transform;
       sceneEffectRoot = effectGo.transform;
    }

    /// <summary>
    /// 加载场景通用配置完毕
    /// </summary>
    public void OnLoadedSceneConfig(object asset)
    {
        if (null == asset)
        {
            Debug.LogError("加载配置文件:" + GameConst.SceneConfig);
            return;
        }
        var origin = asset as GameObject;
        var data = GameObject.Instantiate<GameObject>(origin);
        data.transform.SetParent(transform);
        sceneConfig = data.GetComponent<AutoChessConfig>();
        AutoChessManager.Ins.InitArrowMesh(sceneEffectRoot);
    }

    /// <summary>
    /// 销毁管理器
    /// </summary>
    public void Release()
    {
        Yunchang.EventManager.RemoveEventListener<bool, List<GameObject>>(CommonEvent.PUSH_SHOP_GRID_ROOT, RegisterShopGridRoot);
        loadEventManager.Uninitialize();
        loadEventManager = null;
        //直接全部销毁 
        GameObject.Destroy(gridUnitRoot.gameObject);
        GameObject.Destroy(heroUnitRoot.gameObject);
        GameObject.Destroy(shipUnitRoot.gameObject);
        GameObject.Destroy(sceneEffectRoot.gameObject);
        actionCtr.Relase();
        AutoChessManager.Ins.ClearAllEffect();
    }

    //刷新商店格子 父节点
    private void RegisterShopGridRoot(bool upDown, List<GameObject> roots)
    {
        for (int i = 0; i < gameAutoChessField.AutoChessMapMgr.shopGrids.Count; i++)
        {
            var grid = gameAutoChessField.AutoChessMapMgr.shopGrids[i];
            var parent = upDown ? roots[i].transform : gridUnitRoot;//打开了页面，把格子放上去
           // grid.Display.RefreshRoot(parent, upDown);
            ActorEventHelper.SendGridRootChange(grid,parent,upDown);
        }
    }

    void Update()
    {
        if (acMger != null)
        {
            acMger.Tick(Time.deltaTime);
        }
        if (gameAutoChessField == null)
            return;
        gameAutoChessField.Tick();

        actionCtr.Tick();//最后更新流程队列

        loadEventManager.Tick();
    }

    private void OnApplicationPause(bool pause)
    {
        if (pause)//离开
        {
        }
        else//进入
        {
            //检测当前状态 战斗状态的话直接显示结果
            Debug.LogError("");
        }
    }
    #region renderer

    /// <summary>
    /// 链接战场的时候
    /// </summary>
    /// <param name="gameModeAutoChessField"></param>
    public void OnConnect(AutoChessFieldCtr gameModeAutoChessField)
    {
        gameAutoChessField = gameModeAutoChessField;
    }

    public void OnDisconnect()
    {
        if (gameAutoChessField != null)
        {
            gameAutoChessField = null;
        }
    }

    //TODO need remove 
    private RendererPool renderPool;
    public void GetShipRender()
    {
        
    }
    public void RefreshRenderer()
    {
    }

    #endregion

}
